package common;
import java.sql.*;
/**
 * 数据库公共类
 * @author xieyihong
 * @date 2020-4-7
 */
public class DBUtil {
	//成员变量：静态变量   实例变量 全局变量
	//局部变量   块变量
   private Connection conn = null;
   private Statement stmt = null;
   private ResultSet rs = null;
   private String className= "com.mysql.jdbc.Driver";
   
   private final static String url="jdbc:mysql://localhost:3306/testdb?CharterEncoding=utf-8";
   private final static String user="root";
   private final static String password="123456";
   /**
    * 1.加载数据库驱动程序
    */
   public DBUtil() {
      try {
		Class.forName(className);
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
   }
  /**
   * 2.连接数据库
   * @return
   */
 public Connection getConnection() {
	try {
		conn = DriverManager.getConnection(url, user, password);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return conn;
	 
 }
 /**
  * 3.创建发送sql命令的对象
  * @return
  */
  public Statement getStatement() {
	  try {
		  if(conn == null) {
		    getConnection();
		  }
		  stmt = conn.createStatement();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return stmt;
	  
  }
  /**
   * 4.构造sql命令并发送到数据库(insert,update,delete)
   * @param sql
   * @return
   */
public int executeUpdate(String sql) {
	int result = -1;
	try {
		if(stmt == null) {
			getStatement();
		}
	 result = stmt.executeUpdate(sql);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return result;
	
}
/**
 * 执行sql(select)
 * @param sql
 * @return
 */
public ResultSet executeQuery(String sql) {
	try {
		if(rs == null) {
			getStatement();
		}
		rs = stmt.executeQuery(sql);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return rs;
	}
public void closeDB() {
	try{
		if(stmt != null){
			stmt.close();
		}
		if(conn != null){
			conn.close();
		}
		if(rs != null){
			rs.close();
		}
		
	}catch(SQLException e){
		e.printStackTrace();
	}
}

}
